package com.seashop.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.seashop.constant.ThirdConstant;
import lombok.extern.slf4j.Slf4j;

/**
 * @author moredln
 * @desc 阿里短信
 * @date 2020-09-03 10:48
 */
@Slf4j
public class MessageSendUtil {

    private static CommonRequest request;

    private static IAcsClient client;

    static {
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            // 初始化acsClient
            client = new DefaultAcsClient(DefaultProfile.getProfile(ThirdConstant.ALIYUN_MESSAGE_REGION_ID, ThirdConstant.ALIYUN_MESSAGE_ACCESS_KEY, ThirdConstant.ALIYUN_MESSAGE_ACCESS_SECRET));
            // 组装请求对象-具体描述见控制台-文档部分内容
            request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", ThirdConstant.ALIYUN_MESSAGE_REGION_ID);
            request.putQueryParameter("SignName", ThirdConstant.ALIYUN_MESSAGE_SIGN);
        } catch (Exception e) {
            log.error("smsUtil工具初始化失败");
        }
    }

    public static boolean sendCodeMsg(String mobile, String content, String template) {
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("TemplateParam", content);
        request.putQueryParameter("TemplateCode", template);
        try {
            CommonResponse commonResponse = client.getCommonResponse(request);
            log.info(String.format("发送短信响应----->%s", commonResponse.getData()));
            if (200 == commonResponse.getHttpStatus()) {
                log.info("短信发送成功");
                return true;
            }
        } catch (ClientException e) {
            log.info(String.format("调用阿里云短信平台失败----->%s", e.getMessage()));
            e.printStackTrace();
        }
        return false;
    }

}
